<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/blog/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/blog/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/blog/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/blog/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="TensorFlow,">










<meta name="description" content="本文讲解《Google工程师亲授 Tensorflow2.0－入门到进阶》的第二章，Tensorflow-keras实战视频地址：https://coding.imooc.com/class/chapter/344.html#Anchor">
<meta name="keywords" content="TensorFlow">
<meta property="og:type" content="article">
<meta property="og:title" content="【第二章】Google工程师亲授 Tensorflow2.0－入门到进阶——Tensorflow-keras实战">
<meta property="og:url" content="https://aiolos123.gitee.io/blog/2019/08/13/tensorFlow-step-by-step-2/index.html">
<meta property="og:site_name" content="Aiolos">
<meta property="og:description" content="本文讲解《Google工程师亲授 Tensorflow2.0－入门到进阶》的第二章，Tensorflow-keras实战视频地址：https://coding.imooc.com/class/chapter/344.html#Anchor">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20190814055026194.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20190814055249658.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20190830061641724.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20190830110226002.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20190830113913429.jpg">
<meta property="og:updated_time" content="2019-10-24T08:58:38.328Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="【第二章】Google工程师亲授 Tensorflow2.0－入门到进阶——Tensorflow-keras实战">
<meta name="twitter:description" content="本文讲解《Google工程师亲授 Tensorflow2.0－入门到进阶》的第二章，Tensorflow-keras实战视频地址：https://coding.imooc.com/class/chapter/344.html#Anchor">
<meta name="twitter:image" content="https://aiolos123.gitee.io/blog/images/20190814055026194.jpg">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/blog/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://aiolos123.gitee.io/blog/2019/08/13/tensorFlow-step-by-step-2/">





  <title>【第二章】Google工程师亲授 Tensorflow2.0－入门到进阶——Tensorflow-keras实战 | Aiolos</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/blog/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Aiolos</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">记录我的成长点滴</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/blog/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/blog/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/blog/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/blog/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://aiolos123.gitee.io/blog/blog/2019/08/13/tensorFlow-step-by-step-2/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="aiolos">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/blog/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Aiolos">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">【第二章】Google工程师亲授 Tensorflow2.0－入门到进阶——Tensorflow-keras实战</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2019-08-13T05:59:13+08:00">
                2019-08-13
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/TensorFlow/" itemprop="url" rel="index">
                    <span itemprop="name">TensorFlow</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>本文讲解《Google工程师亲授 Tensorflow2.0－入门到进阶》的第二章，Tensorflow-keras实战<br>视频地址：<a href="https://coding.imooc.com/class/chapter/344.html#Anchor" target="_blank" rel="noopener">https://coding.imooc.com/class/chapter/344.html#Anchor</a></p>
<a id="more"></a>
<h1 id="说明"><a href="#说明" class="headerlink" title="说明"></a>说明</h1><h2 id="课程内容安排方式"><a href="#课程内容安排方式" class="headerlink" title="课程内容安排方式"></a>课程内容安排方式</h2><blockquote>
<p>实战与理论并存，实战为主，理论为辅</p>
</blockquote>
<h2 id="课程代码的TensorFlow版本"><a href="#课程代码的TensorFlow版本" class="headerlink" title="课程代码的TensorFlow版本"></a>课程代码的TensorFlow版本</h2><ol>
<li>大部分代码是TensorFlow 2.0的</li>
<li>课程以tf.keras API为主，因而部分代码可以在tf1.3+运行</li>
<li>另有少量TensorFlow 1.x 版本代码，方便读懂老代码</li>
</ol>
<h1 id="Tensorflow-keras理论部分"><a href="#Tensorflow-keras理论部分" class="headerlink" title="Tensorflow-keras理论部分"></a>Tensorflow-keras理论部分</h1><h2 id="TensorFlow-keras简介"><a href="#TensorFlow-keras简介" class="headerlink" title="TensorFlow-keras简介"></a>TensorFlow-keras简介</h2><h3 id="keras-是什么？"><a href="#keras-是什么？" class="headerlink" title="keras 是什么？"></a>keras 是什么？</h3><ol>
<li>Francois Chollet于2014-2015年编写的，基于python的高级神经网络API，它不是一个完整的库；</li>
<li>keras必须有后端才可以运行。常以TensorFlow、CNTK或者Theano为后端运行。 后端是可以切换的，现在多用TensorFlow</li>
<li>keras极方便于快速实验，帮助用户以最少的时间验证自己的想法</li>
</ol>
<h3 id="TensorFlow-keras是什么？"><a href="#TensorFlow-keras是什么？" class="headerlink" title="TensorFlow-keras是什么？"></a>TensorFlow-keras是什么？</h3><ol>
<li>TensorFlow内部对keras API规范的实现</li>
<li>相对于以TensorFlow为后端的keras，TensorFlow-keras与TensorFlow结合更加紧密</li>
<li>实现在tf.keras空间下</li>
</ol>
<h3 id="TensorFlow-keras与keras的联系"><a href="#TensorFlow-keras与keras的联系" class="headerlink" title="TensorFlow-keras与keras的联系"></a>TensorFlow-keras与keras的联系</h3><ol>
<li>基于同一套API。 所以keras的程序可以通过导入方式轻松转为tf.keras程序；反之不可以，因为tf.keras有其他特性</li>
<li>规范是一致的。 相同的JSON和HDF5模型序列化格式和语义</li>
</ol>
<h3 id="TensorFlow-keras与keras的区别"><a href="#TensorFlow-keras与keras的区别" class="headerlink" title="TensorFlow-keras与keras的区别"></a>TensorFlow-keras与keras的区别</h3><ol>
<li>Tf.keras全面支持eager mode。只用keras.Sequential和keras.Model时没有影响；自定义Model内部运算逻辑时有影响；Tf底层API可以使用keras的model.fit等抽象；tf.keras更适用于研究人员</li>
<li>Tf.keras支持基于tf.data的模型训练</li>
<li>Tf.keras支持TPU训练</li>
<li>Tf.keras支持tf.distribution中的分布式策略</li>
<li>Tf.keras可以与TensorFlow中的estimator集成</li>
<li>Tf.keras可以保存为SavedModel</li>
</ol>
<h3 id="如何选择TensorFlow-keras与keras"><a href="#如何选择TensorFlow-keras与keras" class="headerlink" title="如何选择TensorFlow-keras与keras"></a>如何选择TensorFlow-keras与keras</h3><ol>
<li>如果想用TensorFlow-keras的任何一个特性，那么选择TensorFlow-keras</li>
<li>如果后端互换性更重要，那么选择keras</li>
<li>如果都不重要，那就随便选择</li>
</ol>
<h2 id="分类问题"><a href="#分类问题" class="headerlink" title="分类问题"></a>分类问题</h2><blockquote>
<p>分类问题预测的是类别，模型的输出是概率分布</p>
</blockquote>
<p>三分类问题例子：[0.2,0.7,0.1]</p>
<h2 id="回归问题"><a href="#回归问题" class="headerlink" title="回归问题"></a>回归问题</h2><blockquote>
<p>回归问题预测的是值，模型的输出是一个实数值</p>
</blockquote>
<h2 id="目标函数"><a href="#目标函数" class="headerlink" title="目标函数"></a>目标函数</h2><ol>
<li>为什么需要目标函数？<blockquote>
<p>对大部分机器学习的模型来说，都是逐步调整参数来逼近正确值</p>
</blockquote>
</li>
</ol>
<p><strong>目标函数可以帮助精确衡量模型的好坏</strong></p>
<ol start="2">
<li>对分类问题而言，目标函数需要衡量目标类别与当前预测的差距</li>
</ol>
<p>例子： </p>
<p>三分类问题输出的预测值概率分布：[0.2,0.7,0.1]<br>三分类真实类别转换为真实值概率分布：2 –&gt; one_hot编码 –&gt; [0,0,1]</p>
<blockquote>
<p>one_hot编码: 把正整数变为向量表达。生成一个长度不小于正整数的向量(对分类问题，长度为向量的长度)，只有正整数的位置处为1，其余位置都是0。</p>
</blockquote>
<ol start="3">
<li><p>对回归问题而言，目标函数需要衡量预测值与真实值的差距</p>
</li>
<li><p>目标函数的作用：模型的训练就是调整参数，使得目标函数逐渐变小的过程</p>
</li>
</ol>
<h2 id="损失函数"><a href="#损失函数" class="headerlink" title="损失函数"></a>损失函数</h2><ol>
<li><p>对分类问题而言，常用的损失函数有如下2个：<br><img src="/blog/images/20190814055026194.jpg" alt="分类问题常用的损失函数"><br><img src="/blog/images/20190814055249658.jpg" alt="分类问题常用的损失函数"></p>
</li>
<li><p>对回归问题而言，常用的损失函数有：平方差损失、绝对值损失</p>
</li>
</ol>
<h2 id="神经网络"><a href="#神经网络" class="headerlink" title="神经网络"></a>神经网络</h2><h2 id="激活函数"><a href="#激活函数" class="headerlink" title="激活函数"></a>激活函数</h2><h2 id="批归一化"><a href="#批归一化" class="headerlink" title="批归一化"></a>批归一化</h2><h2 id="Dropout"><a href="#Dropout" class="headerlink" title="Dropout"></a>Dropout</h2><h2 id="Wide-amp-Deep-模型"><a href="#Wide-amp-Deep-模型" class="headerlink" title="Wide &amp; Deep 模型"></a>Wide &amp; Deep 模型</h2><h2 id="超参数搜索"><a href="#超参数搜索" class="headerlink" title="超参数搜索"></a>超参数搜索</h2><h1 id="Tensorflow-keras实战部分"><a href="#Tensorflow-keras实战部分" class="headerlink" title="Tensorflow-keras实战部分"></a>Tensorflow-keras实战部分</h1><h2 id="统一import需要的库"><a href="#统一import需要的库" class="headerlink" title="统一import需要的库"></a>统一import需要的库</h2><figure class="highlight haskell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta"># 统一import需要的库</span></span><br><span class="line"><span class="keyword">import</span> matplotlib <span class="keyword">as</span> mpl</span><br><span class="line"><span class="keyword">import</span> matplotlib.pyplot <span class="keyword">as</span> plt</span><br><span class="line"><span class="meta"># 设置matplotlib可以在notebook中绘制图像</span></span><br><span class="line">%matplotlib inline</span><br><span class="line"><span class="keyword">import</span> numpy <span class="keyword">as</span> np</span><br><span class="line"><span class="keyword">import</span> sklearn</span><br><span class="line"><span class="keyword">import</span> pandas <span class="keyword">as</span> pd</span><br><span class="line"><span class="keyword">import</span> os,sys,time</span><br><span class="line"><span class="keyword">import</span> tensorflow <span class="keyword">as</span> tf</span><br><span class="line"><span class="title">from</span> tensorflow <span class="keyword">import</span> keras</span><br><span class="line"></span><br><span class="line"><span class="meta"># 打印各库版本信息</span></span><br><span class="line"><span class="title">print</span>(tf.__version__)</span><br><span class="line"><span class="title">print</span>(sys.version_info)</span><br><span class="line"><span class="title">for</span> <span class="keyword">module</span> in mpl,np,pd,sklearn,tf,keras:</span><br><span class="line">    print(<span class="title">module</span>.<span class="title">__name__</span>,<span class="title">module</span>.<span class="title">__version__</span>)</span><br></pre></td></tr></table></figure>

<h2 id="keras搭建分类模型"><a href="#keras搭建分类模型" class="headerlink" title="keras搭建分类模型"></a>keras搭建分类模型</h2><blockquote>
<p>完整代码见：344_01_tf_keras_classification_model</p>
</blockquote>
<ol>
<li><p>导入数据集</p>
<figure class="highlight nix"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 导入分类问题的数据集</span></span><br><span class="line"><span class="attr">fashion_mnist</span> = keras.datasets.fashion_mnist</span><br><span class="line"><span class="comment"># 拆分为训练集和测试集</span></span><br><span class="line">(x_train_all,y_train_all),(x_test,y_test) = fashion_mnist.load_data()</span><br><span class="line"><span class="comment"># 将训练集再次拆分为训练集和验证集</span></span><br><span class="line">x_valid,<span class="attr">x_train</span> = x_train_all[:<span class="number">5000</span>],x_train_all[<span class="number">5000</span>:]</span><br><span class="line">y_valid,<span class="attr">y_train</span> = y_train_all[:<span class="number">5000</span>],y_train_all[<span class="number">5000</span>:]</span><br></pre></td></tr></table></figure>
</li>
<li><p>查看数据集</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 展示数据集中的图像，了解数据集是机器学习的一个重要工作</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">show_single_image</span><span class="params">(img_arr)</span>:</span></span><br><span class="line">    plt.imshow(img_arr,cmap=<span class="string">"binary"</span>)</span><br><span class="line">    plt.show()</span><br><span class="line"></span><br><span class="line">show_single_image(x_train[<span class="number">0</span>])</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">show_imgs</span><span class="params">(n_rows,n_cols,x_data,y_data,class_names)</span>:</span></span><br><span class="line">    <span class="comment"># 验证</span></span><br><span class="line">    <span class="keyword">assert</span> len(x_data) == len(y_data)</span><br><span class="line">    <span class="keyword">assert</span> n_rows * n_clos &lt; len(x_data)</span><br><span class="line">    <span class="comment"># 定义大图片的大小</span></span><br><span class="line">    plt.figure(figsize = (n_cols * <span class="number">1.4</span>,n_rows * <span class="number">1.6</span>))</span><br><span class="line">    <span class="comment"># 每行每列放置图片，将小图加到大图上</span></span><br><span class="line">    <span class="keyword">for</span> row <span class="keyword">in</span> range(n_rows):</span><br><span class="line">        <span class="keyword">for</span> col <span class="keyword">in</span> range(n_cols):</span><br><span class="line">            <span class="comment"># 每一张图片的index</span></span><br><span class="line">            index = n_cols * row + col</span><br><span class="line">            plt.subplot(n_rows,n_cols,index+<span class="number">1</span>)</span><br><span class="line">            plt.imshow(x_data[index],cmap=<span class="string">"binary"</span>,</span><br><span class="line">                      interpolation = <span class="string">"nearest"</span>)</span><br><span class="line">            plt.axis(<span class="string">"off"</span>)</span><br><span class="line">            plt.title(class_names[y_data[inddex]])</span><br><span class="line">    plt.show()</span><br><span class="line"></span><br><span class="line">class_names = [<span class="string">'T-shirt'</span>,<span class="string">'Trouser'</span>,<span class="string">'Pullover'</span>,<span class="string">'Dress'</span>,</span><br><span class="line">              <span class="string">'Coat'</span>,<span class="string">'Sandal'</span>,<span class="string">'Shirt'</span>,<span class="string">'Sneaker'</span>,</span><br><span class="line">              <span class="string">'Bag'</span>,<span class="string">'Ankle boot'</span>]</span><br><span class="line"></span><br><span class="line">show_imgs(<span class="number">3</span>,<span class="number">5</span>,x_train,y_train,class_names)</span><br></pre></td></tr></table></figure>
</li>
<li><p>使用Sequential构建模型<br>Sequential API文档地址：<a href="https://tensorflow.google.cn/versions/r2.0/api_docs/python/tf/keras/Sequential" target="_blank" rel="noopener">https://tensorflow.google.cn/versions/r2.0/api_docs/python/tf/keras/Sequential</a></p>
<figure class="highlight vala"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta"># 使用Sequential构建模型</span></span><br><span class="line"><span class="meta"># Sequential API地址：https://tensorflow.google.cn/versions/r2.0/api_docs/python/tf/keras/Sequential</span></span><br><span class="line"></span><br><span class="line"><span class="meta"># 创建Sequential对象</span></span><br><span class="line">model = keras.models.Sequential()</span><br><span class="line"><span class="meta"># 向Sequential对象中添加输入层,通过Flatten将28*28的二维矩阵展开为一维向量</span></span><br><span class="line">model.add(keras.layers.Flatten(input_shape=[<span class="number">28</span>,<span class="number">28</span>]))</span><br><span class="line"><span class="meta"># 添加全连接层,激活函数设置为relu</span></span><br><span class="line">model.add(keras.layers.Dense(<span class="number">300</span>,activation = <span class="string">'relu'</span>))</span><br><span class="line"><span class="meta"># 添加全连接层</span></span><br><span class="line">model.add(keras.layers.Dense(<span class="number">100</span>,activation = <span class="string">'relu'</span>))</span><br><span class="line"><span class="meta"># 添加输出层</span></span><br><span class="line">model.add(keras.layers.Dense(<span class="number">10</span>, activation = <span class="string">'softmax'</span>))</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="meta"># relu: y = max(0,x)</span></span><br><span class="line"><span class="meta"># softmax: 将向量变成概率分布。如向量x 为 [x1,x2,x3]，</span></span><br><span class="line"><span class="meta">#          则softmax的输出 y = [e^x1/sum,e^x2/sum,e^x3/sum],其中sum = e^x1 + e^x2 + e^x3</span></span><br><span class="line"></span><br><span class="line"><span class="meta"># 计算目标函数</span></span><br><span class="line"><span class="meta"># resone for sparse：y-&gt; index, y-&gt;one_hot-&gt;[]</span></span><br><span class="line">model.compile(loss=<span class="string">"sparse_categorical_crossentropy"</span>,</span><br><span class="line">             optimizer = <span class="string">"sgd"</span>,</span><br><span class="line">             metrics = [<span class="string">"accuracy"</span>])</span><br></pre></td></tr></table></figure>
</li>
<li><p>查看模型中的信息</p>
<figure class="highlight vala"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta"># 查看模型的层数</span></span><br><span class="line">model.layers</span><br><span class="line"></span><br><span class="line"><span class="meta"># 打印模型的架构</span></span><br><span class="line">model.summary()</span><br><span class="line"></span><br><span class="line"><span class="meta"># 全连接层的参数个数是如何计算出来的</span></span><br><span class="line"><span class="meta"># [None,784]  * W + b --&gt; [None,300]</span></span><br><span class="line"><span class="meta"># 其中: w.shape = [784,300], b = [300]，所以 235500 = 784*300+300</span></span><br></pre></td></tr></table></figure>
</li>
<li><p>开始训练模型</p>
</li>
</ol>
<figure class="highlight jboss-cli"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 通过fit函数开始训练模型，遍历10次训练集</span></span><br><span class="line"><span class="keyword">history</span> = model.fit<span class="params">(x_train,y_train,<span class="attr">epochs</span> = 10,</span></span><br><span class="line"><span class="params">         <span class="attr">validation_data</span> = (x_valid,y_valid)</span>)</span><br></pre></td></tr></table></figure>

<ol start="6">
<li>训练过程中指标图示的打印<figure class="highlight less"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="selector-tag">def</span> <span class="selector-tag">plot_learning_curves</span>(history):</span><br><span class="line">    <span class="selector-tag">pd</span><span class="selector-class">.DataFrame</span>(history.history)<span class="selector-class">.plot</span>(figsize=(<span class="number">8</span>,<span class="number">5</span>))</span><br><span class="line">    <span class="selector-tag">plt</span><span class="selector-class">.grid</span>(True)</span><br><span class="line">    <span class="selector-tag">plt</span><span class="selector-class">.gca</span>()<span class="selector-class">.set_ylim</span>(<span class="number">0</span>,<span class="number">1</span>)</span><br><span class="line">    <span class="selector-tag">plt</span><span class="selector-class">.show</span>()</span><br><span class="line"><span class="selector-tag">plot_learning_curves</span>(history)</span><br></pre></td></tr></table></figure>

</li>
</ol>
<p><img src="/blog/images/20190830061641724.jpg" alt="训练过程中指标图示的打印"></p>
<ol start="7">
<li>数据归一化<figure class="highlight elm"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"># 完整代码见<span class="number">344</span>_02_tf_keras_classification_model-normalize</span><br><span class="line"></span><br><span class="line"># 数据归一化  x = (x - u) /std. u为均值；std为方差</span><br><span class="line"><span class="title">from</span> sklearn.preprocessing <span class="keyword">import</span> StandardScaler</span><br><span class="line"><span class="title">scaler</span> = <span class="type">StandardScaler</span>()</span><br><span class="line"># x_train:[<span class="type">None</span>,<span class="number">28</span>,<span class="number">28</span>] <span class="comment">--&gt; [None,784]</span></span><br><span class="line"># 对训练集、验证集、测试集进行归一化</span><br><span class="line"><span class="title">x_train_scaled</span> = scaler.fit_transform(</span><br><span class="line">   x_train.<span class="keyword">as</span><span class="keyword">type</span>(np.float32).reshape(-1,1)).reshape(-1,28,28)</span><br><span class="line"><span class="title">x_valid_scaled</span> = scaler.transform(x_valid.<span class="keyword">as</span><span class="keyword">type</span>(np.float32).reshape(-1,1)).reshape(-1,28,28)</span><br><span class="line"><span class="title">x_test_scaled</span> = scaler.transform(x_test.<span class="keyword">as</span><span class="keyword">type</span>(np.float32).reshape(-1,1)).reshape(-1,28,28)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"># <span class="number">5.</span> 开始训练模型（使用归一化后的数据）,通过fit函数，遍历<span class="number">10</span>次训练集</span><br><span class="line"><span class="title">history</span> = model.fit(x_train_scaled,y_train,epochs = <span class="number">10</span>,validation_data = (x_valid_scaled,y_valid))</span><br><span class="line"></span><br><span class="line"># 数据归一化后，数据准确率由<span class="number">84.92</span>%上升到<span class="number">86.60</span>%</span><br></pre></td></tr></table></figure>

</li>
</ol>
<h2 id="keras回调函数"><a href="#keras回调函数" class="headerlink" title="keras回调函数"></a>keras回调函数</h2><p><img src="/blog/images/20190830110226002.jpg" alt="回调函数"></p>
<p>回调函数的作用： 模型训练的过程中可以通过回调函数做一些其他事情</p>
<p>完整代码见：344_03_tf_keras_classification_model-callbacks</p>
<h2 id="keras搭建回归模型"><a href="#keras搭建回归模型" class="headerlink" title="keras搭建回归模型"></a>keras搭建回归模型</h2><h2 id="keras搭建深度神经网络"><a href="#keras搭建深度神经网络" class="headerlink" title="keras搭建深度神经网络"></a>keras搭建深度神经网络</h2><h2 id="keras实现wide-amp-deep模型"><a href="#keras实现wide-amp-deep模型" class="headerlink" title="keras实现wide&amp;deep模型"></a>keras实现wide&amp;deep模型</h2><h2 id="keras与scikit-learn实现超参数搜索"><a href="#keras与scikit-learn实现超参数搜索" class="headerlink" title="keras与scikit-learn实现超参数搜索"></a>keras与scikit-learn实现超参数搜索</h2><h1 id="常见错误"><a href="#常见错误" class="headerlink" title="常见错误"></a>常见错误</h1><h2 id="ProfilerNotRunningError-Cannot-stop-profiling-No-profiler-is-running"><a href="#ProfilerNotRunningError-Cannot-stop-profiling-No-profiler-is-running" class="headerlink" title="ProfilerNotRunningError: Cannot stop profiling. No profiler is running."></a>ProfilerNotRunningError: Cannot stop profiling. No profiler is running.</h2><p>错误如下图：<br><img src="/blog/images/20190830113913429.jpg" alt="ProfilerNotRunningError"></p>
<p>错误原因： Windows系统下文件的路径符合使用错误</p>
<blockquote>
<p>if you name your dir with ‘./log/fit/‘ , above codes will pop up error,<br>if you write as ‘.\log\fig&#39; will not pop up error.<br>见 <a href="https://github.com/tensorflow/tensorboard/issues/2279" target="_blank" rel="noopener">https://github.com/tensorflow/tensorboard/issues/2279</a></p>
</blockquote>
<p>解决方案：</p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/blog/tags/TensorFlow/" rel="tag"># TensorFlow</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/blog/2019/08/09/python-distributed-spider-5/" rel="next" title="【第五章】Python分布式爬虫框架Scrapy打造搜索引擎——scrapy爬取知名问答网站">
                <i class="fa fa-chevron-left"></i> 【第五章】Python分布式爬虫框架Scrapy打造搜索引擎——scrapy爬取知名问答网站
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/blog/2019/09/02/full-stack-dev-meituan-with-vue-one/" rel="prev" title="【第一章】Vue全家桶+SSR+Koa2全栈开发美团网">
                【第一章】Vue全家桶+SSR+Koa2全栈开发美团网 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">aiolos</p>
              <p class="site-description motion-element" itemprop="description">Java Spring Hadoop 机器学习</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/blog/archives/">
              
                  <span class="site-state-item-count">126</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/blog/categories/index.html">
                  <span class="site-state-item-count">16</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/blog/tags/index.html">
                  <span class="site-state-item-count">33</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#说明"><span class="nav-number">1.</span> <span class="nav-text">说明</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#课程内容安排方式"><span class="nav-number">1.1.</span> <span class="nav-text">课程内容安排方式</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#课程代码的TensorFlow版本"><span class="nav-number">1.2.</span> <span class="nav-text">课程代码的TensorFlow版本</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#Tensorflow-keras理论部分"><span class="nav-number">2.</span> <span class="nav-text">Tensorflow-keras理论部分</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#TensorFlow-keras简介"><span class="nav-number">2.1.</span> <span class="nav-text">TensorFlow-keras简介</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#keras-是什么？"><span class="nav-number">2.1.1.</span> <span class="nav-text">keras 是什么？</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#TensorFlow-keras是什么？"><span class="nav-number">2.1.2.</span> <span class="nav-text">TensorFlow-keras是什么？</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#TensorFlow-keras与keras的联系"><span class="nav-number">2.1.3.</span> <span class="nav-text">TensorFlow-keras与keras的联系</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#TensorFlow-keras与keras的区别"><span class="nav-number">2.1.4.</span> <span class="nav-text">TensorFlow-keras与keras的区别</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#如何选择TensorFlow-keras与keras"><span class="nav-number">2.1.5.</span> <span class="nav-text">如何选择TensorFlow-keras与keras</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#分类问题"><span class="nav-number">2.2.</span> <span class="nav-text">分类问题</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#回归问题"><span class="nav-number">2.3.</span> <span class="nav-text">回归问题</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#目标函数"><span class="nav-number">2.4.</span> <span class="nav-text">目标函数</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#损失函数"><span class="nav-number">2.5.</span> <span class="nav-text">损失函数</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#神经网络"><span class="nav-number">2.6.</span> <span class="nav-text">神经网络</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#激活函数"><span class="nav-number">2.7.</span> <span class="nav-text">激活函数</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#批归一化"><span class="nav-number">2.8.</span> <span class="nav-text">批归一化</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Dropout"><span class="nav-number">2.9.</span> <span class="nav-text">Dropout</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Wide-amp-Deep-模型"><span class="nav-number">2.10.</span> <span class="nav-text">Wide &amp; Deep 模型</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#超参数搜索"><span class="nav-number">2.11.</span> <span class="nav-text">超参数搜索</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#Tensorflow-keras实战部分"><span class="nav-number">3.</span> <span class="nav-text">Tensorflow-keras实战部分</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#统一import需要的库"><span class="nav-number">3.1.</span> <span class="nav-text">统一import需要的库</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#keras搭建分类模型"><span class="nav-number">3.2.</span> <span class="nav-text">keras搭建分类模型</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#keras回调函数"><span class="nav-number">3.3.</span> <span class="nav-text">keras回调函数</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#keras搭建回归模型"><span class="nav-number">3.4.</span> <span class="nav-text">keras搭建回归模型</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#keras搭建深度神经网络"><span class="nav-number">3.5.</span> <span class="nav-text">keras搭建深度神经网络</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#keras实现wide-amp-deep模型"><span class="nav-number">3.6.</span> <span class="nav-text">keras实现wide&amp;deep模型</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#keras与scikit-learn实现超参数搜索"><span class="nav-number">3.7.</span> <span class="nav-text">keras与scikit-learn实现超参数搜索</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#常见错误"><span class="nav-number">4.</span> <span class="nav-text">常见错误</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#ProfilerNotRunningError-Cannot-stop-profiling-No-profiler-is-running"><span class="nav-number">4.1.</span> <span class="nav-text">ProfilerNotRunningError: Cannot stop profiling. No profiler is running.</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">aiolos</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Gemini</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/blog/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/blog/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/blog/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/blog/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/blog/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/blog/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/blog/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  

  

  

</body>
</html>
